package com.gxuwz.attend.web.servlet;

import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.service.Impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet(name="loginServlet",urlPatterns = "/login")
public class LoginServlet extends BaseHttpServlet {
    private final static String VIEW_MAIN="/WEB-INF/views/index/index.jsp";
    //src/main/webapp/WEB-INF/views/index/indexAdmin.jsp
    private final static String VIEW_MAIN_STU="/WEB-INF/views/index/indexStu.jsp";
    private final static String VIEW_MAIN_INST="/WEB-INF/views/index/indexInst.jsp";
    private final static String VIEW_MAIN_ADMIN="/WEB-INF/views/index/indexAdmin.jsp";
    private final static String VIEW_LOGIN="login.jsp";

    private UserServiceImpl userService;
    @Override
    public void init() throws ServletException{
        super.init();
        userService= AppContext.getBean(UserServiceImpl.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收参数
        String fullname = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        String role = req.getParameter("role").trim();
        System.out.println("role:"+role);
        //System.out.println("接收参数："+fullname+"--------"+password);
        //调用service层方法
        try{
            boolean flag=false;
            flag=userService.query(fullname,password);
            if (flag){
                // 在登录成功后，将用户信息存储在Session中
                HttpSession session = req.getSession();
                session.setAttribute("fullname", fullname);
                session.setAttribute("role", role);
                if("0".equals(role)){
                    System.out.println("这里这里：////////////////////////");
                    super.doDispatch(req,resp,VIEW_MAIN_STU);
                }
                if("1".equals(role)){
                    super.doDispatch(req,resp,VIEW_MAIN_INST);
                }
                if("2".equals(role)){
                    super.doDispatch(req,resp,VIEW_MAIN_ADMIN);
                }
                /*super.doDispatch(req,resp,VIEW_MAIN);
                super.doDispatch(req,resp,VIEW_MAIN_STU);*/
            }else {
                super.doDispatch(req,resp,VIEW_LOGIN);
            }
        }catch (Exception e){
            e.printStackTrace();
            super.doRedirect(req,resp,req.getContextPath()+ErrorPage_500);
        }
    }
}
